package com.lanou3g.ptp.organize.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanou3g.ptp.entity.College;
import com.lanou3g.ptp.organize.mapper.CollegeMapper;
import com.lanou3g.ptp.organize.service.CollegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CollegeServiceImpl implements CollegeService {
    @Autowired
    private CollegeMapper collegeMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${REDIS_COLLEGE_KEY_PREFIX}")
    private String REDIS_COLLEGE_KEY_PREFIX;

    @Value("${REDIS_COLLEGE_KEY_EXPIRE}")
    private Long REDIS_COLLEGE_KEY_EXPIRE;

    @Override
    public void addCollege(College college) {
        college.setCreateTime(new Date());
        college.setUpdateTime(new Date());
        college.setStatus(0);
        collegeMapper.addCollege(college);
    }

    @Override
    public College findById(Long id) {
        String redisKey = REDIS_COLLEGE_KEY_PREFIX + id;
        String sc = redisTemplate.opsForValue().get(redisKey);
        if (sc == null){
            College college =   collegeMapper.findById(id);
            String s = JSON.toJSONString(college);
            redisTemplate.opsForValue().set(redisKey,s,REDIS_COLLEGE_KEY_EXPIRE, TimeUnit.MINUTES);
            return college;
        }else {
            College college = JSON.parseObject(sc, College.class);
            redisTemplate.expire(redisKey,REDIS_COLLEGE_KEY_EXPIRE, TimeUnit.MINUTES);
            return college;
        }
    }

    @Override
    public List<College> findByIds(Long[] ids) {
        List<College> colleges = collegeMapper.findByIds(ids);
        return colleges;
    }

    @Override
    public College findByName(String name) {
        College college = collegeMapper.findByName(name);
        return college;
    }

    @Override
    public List<College> findAll(Integer page,Integer size) {
        Page<College> pages = PageHelper.startPage(page, size);
        List<College> colleges = collegeMapper.findAll();
        return pages;
    }

    @Override
    public void updateById(Long id, College college) {
        college.setUpdateTime(new Date());
        collegeMapper.updateById(id,college);
    }

    @Override
    public void deleteById(Long id) {
        collegeMapper.deleteById(id);
    }

    @Override
    public void deleteByIds(Long[] ids) {
        collegeMapper.deleteByIds(ids);
    }
}
